import requests
from application.config.redis import connect_redis, redis_exists, redis_get, redis_set
from application.utils.access_token import redis_access_token, redis_access_token_gzh

'''
    微信access_token获取
    有点像普通token,两个小时可用，每天最多请求5000次
'''


def get_ticket():
    access_token = redis_access_token_gzh()
    url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
    params = {
        'access_token': access_token,
        'type': 'wx_card'
    }
    response = requests.get(url, params=params)
    data = response.json()
    if data['errcode'] == 0:
        ticket = data['ticket']
        return ticket
    else:
        print('获取 ticket 失败，错误信息：{}'.format(data['errmsg']))


# 获取redis中的access_token
def redis_api_ticket():
    if redis_exists(0, 'api_ticket'):
        return redis_get(0, 'api_ticket').decode('utf-8')
    else:
        api_ticket = get_ticket()  # 生成新的access_token
        redis_set(0, 3600, 'api_ticket', api_ticket)  # 过期时间3600秒
        return api_ticket
